package com.wxmit.module.system.service.impl;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.wxmit.base.constant.ShushanConstants;
import com.wxmit.module.system.domain.SysDictData;
import com.wxmit.module.system.mapper.SysDictDataMapper;
import com.wxmit.module.system.service.ISysDictDataService;
import com.wxmit.system.base.core.ShushanServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 字典数据Service业务层处理
 * 
 * @author xiong
 * @date 2022-08-09
 */
@Service
public class SysDictDataServiceImpl extends ShushanServiceImpl<SysDictDataMapper, SysDictData> implements ISysDictDataService
{

    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    @Cacheable(cacheNames = ShushanConstants.BASE_DICT_KEY ,key = "#type", unless = "#result == null")
    @Override
    public List<SysDictData> listByType(@NotNull String type) {
        Assert.notNull(type,"字典类型不能为空！");
        SysDictData dict =  new SysDictData();
        dict.setType(type);
        return sysDictDataMapper.getList(dict);
    }

    @CacheEvict(cacheNames = ShushanConstants.BASE_DICT_KEY,key = "#entity.type")
    @Override
    public boolean save(SysDictData entity) {
        checkUnion(entity);
        return super.save(entity);
    }

    @CacheEvict(cacheNames = ShushanConstants.BASE_DICT_KEY,key = "#entity.type")
    @Override
    public boolean updateById(SysDictData entity) {
        checkUnion(entity);
        return super.updateById(entity);
    }

    @CacheEvict(cacheNames = ShushanConstants.BASE_DICT_KEY,allEntries = true)
    @Override
    public boolean removeByIds(Collection<?> list) {
        return super.removeByIds(list);
    }

    public void checkUnion(SysDictData entity){
        LambdaQueryChainWrapper<SysDictData> lambdaQuery = lambdaQuery();
        lambdaQuery.eq(SysDictData::getValue,entity.getValue());
        lambdaQuery.eq(SysDictData::getType,entity.getType());
        if(Objects.nonNull(entity.getId())){
            lambdaQuery.ne(SysDictData::getId,entity.getId());
        }
        Assert.isTrue(lambdaQuery.count() == 0L,"字典键值不能重复！");
    }
}